#include "ProcessMonitor.h"
#include <QTimer>
#include <QProcess>
#include <QDebug>
ProcessMonitor::ProcessMonitor(const QString &processName, QObject *parent):QObject(parent), m_processName(processName),isRunPre(false)
{
    // 启动定时器，每1秒检查一次进程状态
    QTimer *timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &ProcessMonitor::checkProcess);
    timer->start(1000); // 1秒间隔
}

void ProcessMonitor::checkProcess()
{
    QProcess process;
    process.start("tasklist", QStringList() << "/FI" << "STATUS eq RUNNING");
    if (!process.waitForFinished()) {
        //qDebug() << "Failed to execute tasklist";
        isRunPre = false;
        return;
    }

    QString output = QString::fromLocal8Bit(process.readAllStandardOutput());
    if (!output.contains(m_processName, Qt::CaseInsensitive))
    {
        //qDebug() << "Process" << m_processName << "is not running.";
        if(isRunPre)//上次是运行的
        {
            emit processClosed();
        }
    }
    else
    {
        isRunPre = true;
        //qDebug() << "Process" << m_processName << "is running.";
    }
}
